TOP=$(PWD)

#DIRECTORIES:=$(shell Y=`ls src`; for i in $$Y; do if test -d src/$$i; then echo src/$$i; fi done)
#DIRECTORIES+=bin

DIRECTORIES=$(filter-out %.out %.cpp %makefile %.h, ${wildcard src/*})
DIRECTORIES+=bin

TESTCASES=$(filter-out %gold, ${wildcard test/*})

ifeq ($(findstring opt,$(MAKECMDGOALS)),opt)
    MAKEARGS+=opt
endif

ifeq ($(findstring 64,$(MAKECMDGOALS)),64)
    MAKEARGS+=64
endif

opt 64: all

all: 
	@for i in `find src -name "*.g"`; do \
		export Dir=`dirname $$i`; cd $$Dir; $(MAKE) $(MAKECMDGOALS); cd $(TOP); \
	done
	@for i in `find src -name makefile`; do \
		export Dir=`dirname $$i`; cd $$Dir; $(MAKE) $(MAKECMDGOALS); cd $(TOP); \
	done
	cd bin; $(MAKE) $(MAKECMDGOALS); cd $(TOP);
	
regress:
	@for i in $(TESTCASES); do \
		DIR=`dirname $$i`; BASENAME=`basename $$i`; \
		bin/run -i $$i > /tmp/$$BASENAME.out 2> /tmp/$$BASENAME.err;  \
		if diff /tmp/$$BASENAME.out test/gold/$$BASENAME.out > /tmp/$$BASENAME.diff; then \
			if diff /tmp/$$BASENAME.err test/gold/$$BASENAME.err > /tmp/$$BASENAME.diff; then \
				echo "$$i passed"; \
			else echo "Error: Regression Failed diff /tmp/$$BASENAME.err test/gold/$$BASENAME.err"; \
			fi \
		else echo "Error: Regression Failed diff /tmp/$$BASENAME.out test/gold/$$BASENAME.out"; \
		fi; \
		rm -rf /tmp/$$BASENAME.*; \
	done
	
gentest:
	@for i in $(TESTCASES); do \
		DIR=`dirname $$i`; BASENAME=`basename $$i`; \
		bin/run -i $$i > $$DIR/gold/$$BASENAME.out 2> $$DIR/gold/$$BASENAME.err;  \
	done
	
#all:
#	@echo $(DIRECTORIES)
#	@for i in $(DIRECTORIES); do \
#		cd $$i; $(MAKE) $(MAKECMDGOALS); cd $(TOP); \
#	done
	
clean:
	@echo $(DIRECTORIES)
	@for i in $(DIRECTORIES); do \
	  cd $$i; $(MAKE) clean; cd $(TOP); \
	done
